#include "xmppcore/messageparserfactory.h"
#include "xmppcore/parsingutils.h"

namespace yoohoo_xmppcore {

const QString MessageParser::PATH_MESSAGE_SUBJECT = "message/subject";
const QString MessageParser::PATH_MESSAGE_BODY = "message/body";
const QString MessageParser::PATH_MESSAGE_THREAD = "message/thread";

MessageParser::MessageParser() : _message(0) {
}

bool MessageParser::processText(QString path, QString text) {
	if (PATH_MESSAGE_SUBJECT == path) {
		_subject.setText(text);
		_message->subjects().append(_subject);
		_subject = XmlLangText();
	} else if (PATH_MESSAGE_BODY == path) {
		_body.setText(text);
		_message->bodies().append(_body);
		_body = XmlLangText();
	} else if (PATH_MESSAGE_THREAD == path) {
		_message->setThread(text);
	}

	return true;
}

bool MessageParser::doProcessAttributes(QString path, QList<ParsingAttribute> attributes) {
	if (PATH_MESSAGE_SUBJECT == path) {
		QString xmlLang;
		if (ParsingUtils::readXmlLang(attributes, xmlLang)) {
			_subject.setXmlLang(xmlLang);
		}
	} else if (PATH_MESSAGE_BODY == path) {
		QString xmlLang;
		if (ParsingUtils::readXmlLang(attributes, xmlLang)) {
			_body.setXmlLang(xmlLang);
		}
	} else if (PATH_MESSAGE_THREAD == path) {
		if (attributes.size() > 0)
			return false;

		if (!_message->thread().isEmpty()) {
			return false;
		}
	} else {
		return false;
	}

	return true;
}

Stanza* MessageParser::stanza() {
	if (_message == 0) {
		_message = new Message;
	}

	return _message;
}

bool MessageParser::setType(QString sType) {
	if ("chat" == sType) {
		_message->setMessageType(Message::MessageTypeChat);
	} else if ("groupchat" == sType) {
		_message->setMessageType(Message::MessageTypeGroupChat);
	} else if ("headline" == sType) {
		_message->setMessageType(Message::MessageTypeHeadline);
	} else if ("" == sType || "normal" == sType) {
		_message->setMessageType(Message::MessageTypeNormal);
	} else {
		return false;
	}

	return true;
}

XmppParser* MessageParserFactory::createParser() {
	return new MessageParser;
}

ProtocolKey MessageParserFactory::protocolKey() {
	return Message::PROTOCOL_KEY;
}

}
